//
//  MSOAuthViewController.swift
//  SwiftWeibo
//
//  Created by 牟松 on 16/8/12.
//  Copyright © 2016年 DoNews. All rights reserved.
//

import UIKit
import SVProgressHUD
class MSOAuthViewController: UIViewController {
    
    var webView: UIWebView?
    

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }

    

}

extension MSOAuthViewController {
    
    private func setupUI() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(redirect)"
      
        webView = UIWebView(frame: view.bounds)
        webView?.scalesPageToFit = true
        webView?.delegate = self
        webView?.loadRequest(URLRequest(url: URL(string: urlString)!))
        
        view.addSubview(webView!)
    }
    
    private func close(){
        dismiss(animated: true, completion: nil)
        SVProgressHUD.dismiss()
    }
}
extension MSOAuthViewController: UIWebViewDelegate{
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        if request.url?.absoluteString.hasPrefix(redirect) == false {
            return true
        }
        
        // print("加载请求 --- \(request.url?.absoluteString)")
        // query 就是 URL 中 `?` 后面的所有部分
        // print("加载请求 --- \(request.url?.query)")
        // 2. 从 http://baidu.com 回调地址的`查询字符串`中查找 `code=`
        //    如果有，授权成功，否则，授权失败
        if request.url?.query?.hasPrefix("code=") == false {
            
            print("取消授权")
            close()
            
            return false
        }
        
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        print("授权码 - \(code)")
        // 4. 使用授权码获取[换取] AccessToken
        MSAFNManage.shared.getAccountInfoRequest(codeString: code){ (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            } else {
                
                SVProgressHUD.showInfo(withStatus: "登录成功")
                
                // 下一步做什么？跳转`界面` 通过通知发送登录成功消息
                // 1> 发送通知 - 不关心有没有监听者
                NotificationCenter.default.post(
                    name: NSNotification.Name(rawValue: WBUserLoginSuccess),
                    object: nil)
                
                // 2> 关闭窗口
                self.close()
            }
        }
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
